package lunchy.data.classes;

import java.io.File;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import lunchy.data.interfaces.ILunchyUser;
import lunchy.data.interfaces.ILunchyUsersDAO;

public class CLunchyXMLUsersDAO implements ILunchyUsersDAO
{
	private Document data = null; 
	
	public CLunchyXMLUsersDAO(Document data)
	{
		this.data = data;
	}
	
	public ILunchyUser login(String login, String password)
	{
		if(data != null)
		{
			Node usersNode = data.getFirstChild();
			NodeList userNodes = usersNode.getChildNodes();

			for (int i = 0; i < userNodes.getLength(); i++)
			{
				Node userNode = userNodes.item(i);
				
				if(userNode.getNodeName() == "user")
				{
					NamedNodeMap userAttributes = userNode.getAttributes();
					
					String userLogin = userAttributes.getNamedItem("login").getNodeValue();
					String userPassword = userAttributes.getNamedItem("password").getNodeValue();
					
					if(userLogin.equals(login) && userPassword.equals(password))
					{
						ILunchyUser currentUser = new CLunchyUser(
							Integer.parseInt(userAttributes.getNamedItem("id").getNodeValue()),
							userLogin,
							userAttributes.getNamedItem("name").getNodeValue(),
							userAttributes.getNamedItem("admin").getNodeValue().equals("true")
						);
						
						return currentUser;
					}
				}
			}
		}

		return null;
	}
}
